import { h, render } from "preact";
import { useState } from "preact/hooks";
import css from "./index.scss?raw";
import { ChatMsg } from "./type";
import { TxtMsg, ImgMsg, BaseInfoControl, AddMsgControl, ScaleControl } from "./MsgContent";
function WXC() {
  const [chatMsg, setChatMsg] = useState<ChatMsg[]>([]);
  const msgPush = (data:any) => setChatMsg(chatMsg.concat(data))
  const [ bigLadyInfo, setBigLadyInfo ] = useState({
    name: '二十余禾',
    avatar: '',
    startTime: '',
    mode: 'e-home',
    chatMode: 'Q'
  })
  // 修改放大倍率
  const [scale, setScale] = useState(1)
  return (
    <>
      <div className={`wx-chat-his ${bigLadyInfo.mode}`} style={{transform: `scale(${scale})`}}>
        <div className={"chat-content"}>
          <div className={"chat-list"}>
            <p className={ `date-start ${bigLadyInfo.startTime ? '':'hidden'}`}>{bigLadyInfo.startTime}</p>
            {chatMsg.map((msg) => (
              <div className={"chat-item"} key={msg.id}>
                <div className={"avatar"}>
                  <img src={ bigLadyInfo.avatar } alt="" />
                </div>
                <div className={"msg-content"}>
                  { bigLadyInfo.chatMode === 'Q' ? <div className={"user-name"}>{ bigLadyInfo.name }</div> : <div></div> }
                  {msg.type === "text" ? (
                    <TxtMsg msg={msg.content} />
                  ) : (
                    <ImgMsg src={msg.content} />
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>
        <div className={"chat-handler"}>
            <BaseInfoControl updData={ setBigLadyInfo } />
            <AddMsgControl send={ msgPush }></AddMsgControl>
            <ScaleControl updData={ setScale } val={scale}></ScaleControl>
        </div>
      </div>
    </>
  );
}

class WebComponent extends HTMLElement {
  constructor() {
    super();
    // 初始化 Shadow DOM 并渲染 Preact 组件
    const shadow = this.attachShadow({ mode: "open" });
    const styleEl = document.createElement("style");
    styleEl.innerHTML = css;
    this.shadowRoot?.append(styleEl);
    render(h(WXC, {}), shadow);
  }
}

export default customElements.define("wx-chat-his", WebComponent);
